<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: #6ff;
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    var box = document.getElementsByClassName("box")[0];

    var scrollWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
    var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    var maxLeft = scrollWidth - box.clientWidth;
    var maxTop = scrollHeight - box.clientHeight;

    window.onresize = function () {
        var scrollWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
        var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        var maxLeft = scrollWidth - box.clientWidth;
        var maxTop = scrollHeight - box.clientHeight;
    }

    //按下记录位置
    box.onmousedown = function (e) {

        var e = e || window.event;

        //计算获取
        // var posX = e.pageX - box.offsetLeft;
        // var posY = e.pageY - box.offsetTop;

        //直接获取
        var posX = e.offsetX;
        var posY = e.offsetY;
        console.log(posX, posY);

        //元素跟随鼠标位置移动
        document.onmousemove = function (e) {
            var e = e || window.event;
            var x = e.pageX - posX;
            var y = e.pageY - posY;

            if (x < 0) x = 0;
            if (y < 0) y = 0;
            if (x > maxLeft) x = maxLeft;
            if (y > maxTop) y = maxTop;

            box.style.left = x + "px";
            box.style.top = y + "px";
        }

        //鼠标松开时元素停留在当前位置
        document.onmouseup = function () {
            document.onmousemove = null;
        }
    }

</script>

</html>